<template>
  <ga-modal
    v-model:visible="visible"
    title-align="start"
    :width="800"
    @close="handleCancel(formRef)"
  >
    <template #title>新建{{ imageType[tab] || "公共镜像（标准）" }}</template>
    <ga-spin style="width: 100%" :loading="loading">
      <ga-form ref="formRef" :model="formData">
        <ga-card
          :style="{ backgroundColor: '#F7F9FC' }"
          :header-style="{ paddingRight: '24px' }"
          title="关联镜像"
          :bordered="false"
        >
          <template #extra>
            <ga-link :hoverable="false" @click="() => handleAdd()">
              <template #icon><icon-plus /></template>添加
            </ga-link>
          </template>
          <ga-table
            row-key="id"
            :columns="columns"
            :data="tableData"
            :bordered="false"
            size="small"
            :hoverable="false"
            :pagination="false"
            :scroll="{ y: 220 }"
          >
            <template #resourceId="{ record, rowIndex }">
              <ga-select
                v-model="record.resourceId"
                @change="handleChangePlatform(record, rowIndex)"
                placeholder="请选择平台"
              >
                <ga-option
                  v-for="item in getPlatformOptions"
                  :key="item.id"
                  :value="item.id"
                >
                  {{ item.name }}
                </ga-option>
              </ga-select>
            </template>
            <template #templateId="{ record }">
              <ga-select
                v-model="record.templateId"
                allow-search
                placeholder="请选择镜像"
              >
                <ga-option
                  v-for="item in record?.templateRow"
                  :key="item.id"
                  :value="item.id"
                >
                  {{ item.name }}
                </ga-option>
              </ga-select>
            </template>
            <template #action="{ rowIndex }">
              <ga-link
                status="danger"
                :hoverable="false"
                @click="() => tableData.splice(rowIndex, 1)"
              >
                移除
              </ga-link>
            </template>
          </ga-table>
        </ga-card>
      </ga-form>
    </ga-spin>
    <template #footer>
      <ga-button @click="visible = false">取消</ga-button>
      <ga-button type="primary" @click="handleOk">确定</ga-button>
    </template>
  </ga-modal>
</template>

<script setup>
import { ref, computed, reactive } from "vue";
import { getList } from "@/api/platformMgmt";
import {
  getImageTemplateList,
  createTemplate,
  getImageTypeList,
} from "@/api/operatingSystem";
import { Message } from "@garco-design/web-vue";
import useLoading from "@/hooks/loading";
import { imageType } from "@/constant/index";
import { useRoute } from "vue-router";

const route = useRoute();
const { tab } = route.query;
const { id } = route.params;
const { loading, setLoading } = useLoading(false);
const formRef = ref(null);
const tableData = ref([]);
const platformList = ref([]);
const templateList = ref([]);
const formData = reactive({
  name: "",
  description: "",
});
const props = defineProps({
  templateType: {
    type: String,
    default: "public_standard",
  },
});
const visible = ref(false);
const curId = ref("");
const getPlatformOptions = computed(() => {
  return tab === "nonStandardImage"
    ? renderPlatformList.value
    : resolveOption(renderPlatformList.value);
});
// const getTemplateOptions = computed(() => {
//   return tab === "nonStandardImage"
//     ? resolveTemOption(templateList.value)
//     : templateList.value;
// });
const columns = [
  {
    title: "平台",
    dataIndex: "resourceId",
    slotName: "resourceId",
  },
  {
    title: "镜像",
    dataIndex: "templateId",
    slotName: "templateId",
  },
  {
    title: "操作",
    width: 60,
    slotName: "action",
  },
];
const open = async () => {
  visible.value = true;
  setLoading(true);
  fetchPlatformList();
  fetchStandardImageData();
};
const resolveOption = (data) => {
  return data?.filter((item) => !tableData.value.some((c) => c.resourceId === item.id));
};

// 处理切换平台方法
const handleChangePlatform = async ({ resourceId }, rowIndex) => {
  templateList.value = [];
  tableData.value[rowIndex].templateId = "";
  tableData.value[rowIndex].templateRow = [];
  await fetchTemplateList(resourceId);
  tableData.value[rowIndex].templateRow = templateList.value;
};
// const handleChangeTemplate = async (templateId, rowIndex) => {
//   tableData.value[rowIndex].templateRow = [];
//   tableData.value[rowIndex].templateRow = getTemplateOptions.value;
//   console.log("getTemplateOptions.value", getTemplateOptions.value);
// };

// 获取标准镜像列表
const standardImageResIds = ref([]);
const fetchStandardImageData = async () => {
  try {
    const { data } = await getImageTypeList(
      {
        limit: -1,
        templateType: "public_standard",
      },
      id
    );
    standardImageResIds.value = data.items?.map((item) => item?.resourceId);
  } catch (err) {
    console.log(err);
  }
};
// 获取平台方法
const fetchPlatformList = async () => {
  try {
    const { data } = await getList({ limit: -1 });
    platformList.value = data.items;
  } finally {
    setLoading(false);
  }
};
// render PlatformList
const renderPlatformList = computed(() => {
  if (tab === "nonStandardImage") return platformList.value;
  return platformList.value?.filter(
    (item) => !standardImageResIds.value?.includes(item?.id)
  );
});
// 获取templateList方法
const fetchTemplateList = async (resourceId) => {
  try {
    const { data } = await getImageTemplateList({
      resourceId,
      limit: -1,
      osId: id,
      filterOs: 1,
    });
    templateList.value = data.items;
  } finally {
    setLoading(false);
  }
};
// 处理添加方法
const handleAdd = () => {
  if (tableData.value.length === platformList.value.length) return;
  tableData.value.push({ resourceId: "", templateId: "", templateRow: [] });
};

// 判断函数
const checkAllItemsNotEmpty = (data) => {
  for (const item of data) {
    // 检查 resourceId 是否为空
    if (!item.resourceId) {
      return false;
    }
    // 检查 templateId 是否为空
    if (!item.templateId) {
      return false;
    }
  }
  return true;
};
// 保存
const emits = defineEmits(["fetchData"]);
const handleOk = async () => {
  const arr = tableData.value?.map((item) => ({
    resourceId: item.resourceId,
    templateId: item.templateId,
    templateType: props.templateType,
  }));
  if (arr?.length > 0 && checkAllItemsNotEmpty(arr)) {
    try {
      const { code } = await createTemplate(id, arr);
      if (code === 20000) Message.success("操作成功");
      emits("fetchData");
    } finally {
      visible.value = false;
    }
  } else {
    Message.warning("请选择要关联的镜像或者平台信息");
  }
};
const handleCancel = (formEl) => {
  curId.value = "";
  tableData.value = [];
  formEl.resetFields();
};
defineExpose({ open });
</script>

<style lang="scss" scoped>
:deep(.garco-table-header) {
  background-color: #fff !important;
}
</style>
